
from Blue import lantu
import pytest
import os
from common.ModifyAllure import generate_environment_properties,modify_summary_json
from config.read_config import congfig_read
from flask import Flask,render_template, request,jsonify
from common.ReadExcel import ReadExcel
import json
import io

@lantu.route("/")
def home():
    return render_template('home.html')


@lantu.route('/lianxi')
def lianxi():
    return render_template('lianxi.html')


result=None
file_stream=None
@lantu.route('/upload',methods=['GET','POST'])
def upload():
    uploaded_file=request.files["file"]
    global result
    global file_stream
    if uploaded_file:
        file_stream = io.BytesIO(uploaded_file.read())
        result=ReadExcel(uploaded_file)
        return jsonify({"sucess":"上传成功"})
    
    else:
        return jsonify({"sucess":"上传失败"})
    


@lantu.route('/run_test', methods=['POST'])
def run_test():
    global result
    if result:
        # 使用 json.loads() 解码 JSON 字符串
        try:
            decoded_result = json.loads(result)
        except json.JSONDecodeError as e:
            return jsonify({"error": f"JSON 解码失败: {str(e)}"})

        # 运行测试用例
        pytest.main(["--params={}".format(decoded_result)])

        # 生成 environment.properties 文件
        generate_environment_properties(decoded_result['env_value'])

        # 生成 Allure 报告
        os.system('allure generate ./temps -o ./report --clean')

        configpath = 'config/Transaction.ini'
        TOTAL = congfig_read(configpath).get('测试统计结果', '用例总计')
        PASSED = congfig_read(configpath).get('测试统计结果', '通过数量')
        FAILED = congfig_read(configpath).get('测试统计结果', '失败数量')
        ERROR = congfig_read(configpath).get('测试统计结果', '错误数量')
        SKIPPED = congfig_read(configpath).get('测试统计结果', '跳过数量')
        RERUN = congfig_read(configpath).get('测试统计结果', '失败重试')
        TIME = congfig_read(configpath).get('测试统计结果', '总计用时')

        modify_summary_json(decoded_result['project_name_value'])

        return jsonify({"total": TOTAL, "pass": PASSED, "failed": FAILED, "error": ERROR, "skip": SKIPPED, "rerun": RERUN, "time": TIME})
    else:
        return jsonify({'success': False})



